package com.guangzi.controller;


import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;


// 使当前类 可以通过spring注入

@ServerEndpoint(value = "/websocket/{username}")
@Component
public class MyWebSocket {
    //静态变量,用来记录当前在线连接数,
    private static int onlineCount = 0;

    public MyWebSocket(){}
    // key 代表用户名或其他唯一标识, value 代表对应的WebSocket连接
    private static Map<String,MyWebSocket> webSocketMap=new ConcurrentHashMap<>();
    //用户名
    private String username;
    //当前的httpSession
    private Session session;
    //连接建立成功的方法
    @OnOpen
    public void onOpen(@PathParam("username") String username, Session session){
        this.session = session;
        this.username = username;

        // map key 是唯一的
        if(!webSocketMap.containsKey(username)){
            addOnlineCount(); //在线数加1
            //用户名和当前用户的websocket 放进map
            webSocketMap.put(this.username,this);
            System.out.println("有新的连接加入!!!,当前在线人数为"+getOnlineCount()+webSocketMap+"-------"+username);
        }


    }
    // 连接关闭调用的方法
    @OnClose
   public void onClose(@PathParam("username") String username, Session session){
      webSocketMap.remove(username);
       subOnlineCount();//在线数 减1
       System.out.println("有一连接"+username+"的关闭连接,当前在线人数为"+getOnlineCount());

   }

    /**
     *
     * @param message  客户端发送过来的信息
     * @param session
     */
   @OnMessage
   public void onMessage(@PathParam("username") String username,String message,Session session)throws IOException{
     /*  ObjectMapper objectMapper = new ObjectMapper();
       Map map = objectMapper.readValue(message,Map.class);*/

       System.out.println(username+"来自客户端的消息"+message);
       // sendMessage(username,message); // 点对点
       sendMessage(message); // 广播
   }

   @OnError
   public void onError(Session session,Throwable error){
       System.out.println("发生错误");
       error.printStackTrace();
   }

   // 点对点发送
   public void sendMessage(String username,String message)throws IOException{
       // 保存到数据库
      // 构建对象,保存到数据库
      MyWebSocket webSocket = webSocketMap.get(username);
       webSocket.session.getBasicRemote().sendText(message);
       System.out.println("------ 点对点发送------"+username +"----"+message);



   }
   // 广播类型发送
    public void sendMessage(String message)throws IOException{
        // 保存到数据库
        // 构建对象,保存到数据库
        Set<String> keys = webSocketMap.keySet();

        for (String key:keys){
            MyWebSocket ws = webSocketMap.get(key);
            System.out.println(key+"-----------------"+message+"---------"+this.username);
            ws.sendMessage(key,this.username+" :    "+message);
//            ws.sendMessage(key,message);
        }

    }


   public static synchronized int getOnlineCount(){
       return onlineCount;
   }

    public static synchronized void addOnlineCount() {

       MyWebSocket.onlineCount++;
    }


    public static synchronized void subOnlineCount() {

        MyWebSocket.onlineCount--;
    }


















    }
